<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 目录树 -->
      <el-col
        :lg="4"
        :md="5"
        :sm="6"
        :xs="24"
        class="mb-[12px] !pr-0"
        v-if="showTree"
      >
        <equdevicemodel-tree
          v-model="searchParam.assetTypeId"
          @node-click="search"
          :assetKind="1"
        />
      </el-col>
      <el-col
        :lg="showTree ? 20 : 24"
        :md="showTree ? 19 : 24"
        :sm="showTree ? 18 : 24"
        :xs="24"
      >
        <div class="search-container">
          <el-form :model="searchParam" :inline="true" label-width="63px">
            <el-form-item label="位置">
              <el-tree-select
                placeholder="请输入位置"
                filterable
                v-model="searchParam.locationId"
                :data="locationInfoTree"
                node-key="id"
                clearable
                :props="{ label: 'locationName', children: 'nodes' }"
                check-strictly
                :render-after-expand="false"
              />
            </el-form-item>
            <el-form-item label="设备编码">
              <el-input
                v-model="searchParam.assetCode"
                placeholder="请输入设备编码"
                clearable
                @keyup.enter="search"
              />
            </el-form-item>
            <el-form-item label="设备名称">
              <el-input
                v-model="searchParam.assetName"
                placeholder="请输入设备名称"
                clearable
                @keyup.enter="search"
              />
            </el-form-item>
            <el-form-item label="设备状态">
              <el-select
                v-model="searchParam.assetStatus"
                placeholder="请选择设备状态"
                @keyup.enter="search"
                clearable
              >
                <el-option
                  v-for="item in dictionaryStore.filterDictList('EquipStatus')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="使用部门">
              <SelectOriganizationDangerGrant
                @change="(ids:string) => getSelectIds(ids, '使用部门')"
                :isCheckStrictly="true"
                :isMultiple="false"
                :disabled="false"
                :data="dataObject('使用部门')"
                :selectData="searchParam.usingDepartmentId"
              />
            </el-form-item>
            <el-form-item label="管理部门">
              <SelectOriganizationDangerGrant
                @change="(ids:string) => getSelectIds(ids, '管理部门')"
                :isCheckStrictly="true"
                :isMultiple="false"
                :disabled="false"
                :data="dataObject('管理部门')"
                :selectData="searchParam.manageDepartmentId"
              />
            </el-form-item>

            <div v-if="isExpanded" style="display: inline">
              <el-form-item label="管理人">
                <el-select
                  v-model="searchParam.assetManagerId"
                  placeholder="请选择管理人"
                  clearable
                >
                  <el-option
                    v-for="item in personList"
                    :label="`${item.firstName}`"
                    :value="`${item.id}`"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="维修部门">
                <SelectOriganizationDangerGrant
                  @change="(ids:string) => getSelectIds(ids, '维修部门')"
                  :isCheckStrictly="true"
                  :isMultiple="false"
                  :disabled="false"
                  :data="dataObject('维修部门')"
                  :selectData="searchParam.repairDepartmentId"
                />
              </el-form-item>
              <el-form-item label="维修人">
                <el-select
                  v-model="searchParam.repairManagerId"
                  placeholder="请选择维修人"
                  clearable
                >
                  <el-option
                    v-for="item in personList1"
                    :label="`${item.firstName}`"
                    :value="`${item.id}`"
                  />
                </el-select>
              </el-form-item>
              <!-- <el-form-item label="到货日期">
                <el-date-picker
                  v-model="searchParam.arrivalDateSearch"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  @change="getcreateTime"
                />
              </el-form-item> -->
            </div>

            <el-form-item>
              <el-button type="primary" @click="search"
                ><i-ep-search />搜索</el-button
              >
              <el-button @click="reset"><i-ep-refresh />重置</el-button>
              <!-- <el-button @click="handelTree" type="primary"
                ><i-ep-location />目录树</el-button
              > -->
              <el-button type="primary" @click="toggleSearchArea" link>
                {{ isExpanded ? "收起" : "展开" }}
                <el-icon v-if="isExpanded" class="el-icon--right">
                  <i-ep-arrowUp color="#409EFC" />
                </el-icon>
                <el-icon v-else class="el-icon--right">
                  <i-ep-arrowDown color="#409EFC" />
                </el-icon>
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card
          shadow="never"
          class="table-container relative overflow-visible!"
        >
          <template #header>
            <el-button type="success" plain @click="openDialog()"
              ><i-ep-plus />新增</el-button
            >
            <el-button type="primary" style="display: none"
              >打印二维码</el-button
            >
            <el-button type="primary" style="display: none">导入</el-button>
            <el-button
              @click="
                useDownload('/eam/equAssetInfo/export', '设备台账', searchParam)
              "
            >
              <template #icon><i-ep-download /></template>导出</el-button
            >
            <el-button type="primary" style="display: none"
              >导入模板下载</el-button
            >
            <el-button
              type="danger"
              plain
              :disabled="ids.length === 0"
              @click="handleTableDelete()"
              ><i-ep-delete />删除</el-button
            >
          </template>

          <el-table
            ref="dataTableRef"
            v-loading="loading"
            :data="tableData"
            highlight-current-row
            border
            :maxHeight="tableHeight"
            @selection-change="handleSelectionChange"
            @sort-change="onTableSortChanged"
          >
            <el-table-column type="selection" width="55" align="center" />
            <!-- 表格内容操作 -->
            <template v-for="item in tableColumns" :key="item">
              <TableColumn v-if="item.prop && item.isShow" :column="item">
                <template v-for="slot in Object.keys($slots)" #[slot]="scope">
                  <slot :name="slot" v-bind="scope"></slot>
                </template>
              </TableColumn>
            </template>
            <!-- <el-table-column
              sortable
              label="设备编码"
              prop="assetCode"
              min-width="120"
              show-overflow-tooltip
              align="left"
            >
            </el-table-column>
            <el-table-column
              sortable
              label="设备名称"
              prop="assetName"
              min-width="120"
              show-overflow-tooltip
              align="left"
            >
            </el-table-column> -->

            <!-- <el-table-column
              sortable
              label="品牌"
              prop="assetBrandName"
              min-width="120"
              show-overflow-tooltip
              align="left"
            >
              <template #default="scope">
                {{ scope.row.assetBrandName }}
              </template>
            </el-table-column> -->
            <!-- <el-table-column
              sortable
              label="型号"
              prop="assetModelNo"
              min-width="120"
              show-overflow-tooltip
              align="left"
            >
              <template #default="scope">
                {{ scope.row.assetModelNo }}
              </template>
            </el-table-column>
            <el-table-column
              sortable
              label="设备种类"
              prop="assetTypeCode"
              min-width="120"
              show-overflow-tooltip
              align="left"
            >
              <template #default="scope">
                {{ scope.row.assetTypeName }}
              </template>
            </el-table-column>
            <el-table-column
              sortable
              label="设备类别"
              prop="measuringType"
              min-width="110"
              show-overflow-tooltip
              align="left"
            >
              <template #default="scope">
                {{
                  dictionaryStore.filterDictName(
                    "EquipmentCategory",
                    scope.row.measuringType
                  )
                }}
              </template>
            </el-table-column>
            <el-table-column
              sortable
              label="制造工厂"
              prop="makerName"
              min-width="110"
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                {{ scope.row.makerName || "" }}
              </template>
            </el-table-column> -->
            <!-- <el-table-column
              label="到货日期"
              prop="arrivalDate"
              min-width="180"
              sortable
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                {{
                  scope.row.arrivalDate
                    ? dayjs(scope.row.arrivalDate).format("YYYY-MM-DD")
                    : ""
                }}
              </template>
            </el-table-column> -->

            <!-- <el-table-column
              sortable
              label="管理部门"
              prop="manageDepartmentName"
              min-width="120"
              show-overflow-tooltip
              align="left"
            >
            </el-table-column>

            <el-table-column
              sortable
              label="使用部门"
              prop="usingDepartmentName"
              min-width="120"
              show-overflow-tooltip
              align="left"
            >
            </el-table-column>
            <el-table-column
              sortable
              label="维修部门"
              prop="repairDepartmentName"
              min-width="110"
              show-overflow-tooltip
              align="left"
            >
            </el-table-column>
            <el-table-column
              sortable
              label="设备位置"
              prop="locationName"
              min-width="120"
              show-overflow-tooltip
              align="left"
            >
            </el-table-column>

            <el-table-column
              sortable
              label="设备状态"
              prop="assetStatus"
              min-width="120"
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                {{ useDictionary("EquipStatus", scope.row.assetStatus) }}
              </template>
            </el-table-column> -->

            <el-table-column
              fixed="right"
              label="操作"
              width="110"
              align="center"
            >
              <template #default="scope">
                <el-tooltip
                  :hide-after="0"
                  effect="light"
                  content="查看"
                  placement="top"
                >
                  <el-button
                    type="primary"
                    size="small"
                    link
                    @click="openDialogdetail(scope.row)"
                  >
                    <i-ep-search />
                  </el-button>
                </el-tooltip>
                <el-tooltip
                  :hide-after="0"
                  effect="light"
                  content="编辑"
                  placement="top"
                >
                  <el-button
                    type="primary"
                    size="small"
                    link
                    @click="openDialog(scope.row)"
                  >
                    <i-ep-edit />
                  </el-button>
                </el-tooltip>
                <el-tooltip
                  :hide-after="0"
                  effect="light"
                  content="删除"
                  placement="top"
                >
                  <el-button
                    type="primary"
                    size="small"
                    link
                    @click="deleteItem(scope.row.id)"
                  >
                    <i-ep-delete />
                  </el-button>
                </el-tooltip>

                <!-- <el-button
                  type="primary"
                  size="small"
                  link
                  @click="openDialogdetail(scope.row)"
                  ><i-ep-search />
                  查看
                </el-button>
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="openDialog(scope.row)"
                  ><i-ep-edit />编辑</el-button
                >
                <el-button
                  type="primary"
                  size="small"
                  link
                  style="display: none"
                  @click="openDialog(scope.row)"
                  ><i-ep-edit />文档</el-button
                >
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="deleteItem(scope.row.id)"
                  ><i-ep-delete />删除</el-button
                > -->
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            :background="true"
            :current-page="pageable.pageNum"
            :page-size="pageable.pageSize"
            :page-sizes="[10, 25, 50, 100]"
            :total="pageable.total"
            layout="total, sizes, prev, pager, next, jumper"
            class="mt-[20px]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />

          <el-button
            circle
            style="position: absolute; left: -13px; top: 150px; font-size: 20px"
            class="zhedie"
            @click="handelTree"
          >
            <el-icon v-if="showTree" class="el-icon--right">
              <i-ep-arrowLeft />
            </el-icon>
            <el-icon v-else class="el-icon--right">
              <i-ep-arrowRight />
            </el-icon>
          </el-button>

          <!-- <el-button type="primary" @click="toggleSearchArea" link>
                {{ isExpanded ? "收起" : "展开" }}
                <el-icon v-if="isExpanded" class="el-icon--right">
                  <i-ep-arrowUp color="#409EFC" />
                </el-icon>
                <el-icon v-else class="el-icon--right">
                  <i-ep-arrowDown color="#409EFC" />
                </el-icon>
              </el-button> -->
        </el-card>

        <equdeviceinfo-edit
          :visible="addDialog.visible"
          :title="addDialog.title"
          :assetTypeIdTree="assetTypeIdTree"
          :data="addDialog.data"
          @reset-table="(id:string) => (id?.length ? getTableList() : getTableList())"
          :is-readonly="addDialog.readvisible"
          @change-visible="changeVisible"
        />
      </el-col>
    </el-row>
    <!-- 列设置 -->
    <ColSetting
      v-model:col-setting="tableColumns"
      v-model:search-setting="searchColumns"
      @search-handle="(e:boolean) => (showSearch = e)"
    />
  </div>
</template>

<script setup lang="ts">
import {
  useTable,
  useDownload,
  useDictionary,
  useComputeTableHeight,
} from "@/utils/useTable";
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import { filterOrder } from "@/utils/commonHooks";

import dayjs from "dayjs";

import { Search } from "@element-plus/icons-vue";

defineOptions({
  name: "EQUDEVICELEDGER",
  inheritAttrs: false,
});
// 目录树显隐
const showTree = ref(true);
const handelTree = () => {
  showTree.value = !showTree.value;
};
// 切换搜索折叠
const isExpanded = ref(false);
function toggleSearchArea() {
  isExpanded.value = !isExpanded.value;
}
// 请求参数
const requestApi = "/eam/equAssetInfo/queryByPage";

// 是否需要分页
const pagination = true;
const initParam = reactive({
  assetKind: 1,
  sort: {
    column: "",
    orderBy: "",
  },
});

// 初始化搜索参数数据
const searchParamInit = {
  assetName: "",
  assetCode: "",
  assetTypeId: "",
  locationId: "",
  usingDepartmentId: "",
  assetStatus: "",
  manageDepartmentId: "",
  assetManagerId: "",
  repairManagerId: "",
  checkPerson: "",
  arrivalDateSearch: [],
  arrivalDateStart: "",
  arrivalDateEnd: "",
  assetKind: 1,
};

const deleteParam = {
  api: "/eam/equAssetInfo/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

// 定义tableHeight, 将计算注入dataCallBack回调中
const tableHeight = ref();
function dataCallBack(data: any) {
  setTimeout(() => {
    tableHeight.value = useComputeTableHeight();
  }, 100);
  return data;
}

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
});
// 排序
// 监听表格排序方法
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  console.log(prop, order);

  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };
}
// 监听页面 initParam 改化，重新获取表格数据
watch(() => initParam, getTableList, { deep: true });
const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/eam/equAssetInfo/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开资产台账表单弹窗 */
const assetTypeIdTree = ref("");
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改资产台账";
    getInfo(roleObj.id);
  } else {
    assetTypeIdTree.value = searchParam.value.assetTypeId;
    addDialog.title = "新增资产台账";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开资产台账表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "资产台账详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
    assetTypeIdTree.value = "";
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除该条数据?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await request({
      url: `/eam/equAssetInfo/deleteItem/${id}`,
      method: "post",
    }).then((res) => {
      ElMessage.success("删除成功！");
      search();
    });
  });
}

/** 选择组织机构并赋值id  start **/
function getSelectIds(ids: [] | string, item: string) {
  if (ids) {
    if (item == "使用部门") {
      searchParam.value.usingDepartmentId = ids;
    } else if (item == "管理部门") {
      searchParam.value.manageDepartmentId = ids;
      personList.value = [];
      changeDept(ids, item);
    } else if (item == "维修部门") {
      searchParam.value.repairDepartmentId = ids;
      personList1.value = [];
      changeDept(ids, item);
    }
  } else {
    if (item == "使用部门") {
      searchParam.value.usingDepartmentId = "";
    } else if (item == "管理部门") {
      searchParam.value.manageDepartmentId = "";
      searchParam.value.assetManagerId = "";
      personList.value = [];
    } else if (item == "维修部门") {
      searchParam.value.repairDepartmentId = "";
      searchParam.value.repairManagerId = "";
      personList1.value = [];
    }
  }
}

// 点击组织机构 选择人员
const personList = ref([]);
const personList1 = ref([]);
const changeDept = async (id, name) => {
  if (id) {
    const res = await request({
      url: "/system/sysUser/getList ",
      method: "post",
      data: {
        departmentId: id,
      },
    });
    if (name == "管理部门") {
      personList.value = res.data;
      // personList.value.map((item: any) => {
      //   item.label = `${item.firstName}`;
      //   item.value = `${item.id}`;
      // });
    }
    if (name == "维修部门") {
      personList1.value = res.data;
      // personList.value.map((item: any) => {
      //   item.label = `${item.firstName}`;
      //   item.value = `${item.id}`;
      // });
    }
  }
};
const dataObject = (item: string) => {
  return {
    name:
      item == "使用部门"
        ? "使用部门"
        : item == "管理部门"
        ? "管理部门"
        : "维修部门",
    defaultProps: {
      children: "nodes",
      label: "organizationName",
      value: "id",
    },
    api: "/system/sysOrganization/getUsableTree",
  };
};

// 获取位置信息下拉树
const locationInfoTree = ref([]);
const getLocationInfoTree = async () => {
  const { data } = await request({
    url: "/eam/locationInfo/getTree",
    method: "POST",
    data: {
      enabled: 1,
    },
  });
  locationInfoTree.value = data;
};
// 获取制造工厂列表
const makerList: any = ref([]);
const getMakerList = async () => {
  request({
    url: `/eam/eammaker/getList`,
    method: "post",
    data: {},
  })
    .then((res) => {
      makerList.value = res.data;
    })
    .catch((res) => {
      console.log(res);
    });
};

// 处理时间
function getcreateTime(data: any) {
  if (data) {
    searchParam.value.arrivalDateStart = data[0];
    searchParam.value.arrivalDateEnd = data[1];
  } else {
    searchParam.value.arrivalDateStart = "";
    searchParam.value.arrivalDateEnd = "";
  }
}
onMounted(() => {
  getLocationInfoTree();
  getMakerList();
});

// 接收 columns 并设置为响应式
const tableColumns = reactive([
  {
    prop: "fixedAssetCode",
    label: "U9编码",
    minWidth: 110,
    isShow: true,
    align: "left",
  },
  {
    prop: "assetCode",
    label: "设备编码",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
  {
    prop: "assetName",
    label: "设备名称",
    minWidth: 140,
    isShow: true,
    align: "left",
  },
  {
    prop: "assetTypeName",
    label: "设备种类",
    minWidth: 110,
    isShow: true,
    align: "center",
  },
  {
    prop: "assetModelNo",
    label: "型号",
    minWidth: 120,
    isShow: true,
    align: "left",
  },
  {
    prop: "assetSpecification",
    label: "规格",
    minWidth: 130,
    isShow: true,
    align: "left",
  },
  {
    prop: "quantityUnit",
    label: "单位",
    minWidth: 60,
    align: "center",
    isShow: true,
    render: (scope: any) =>
      dictionaryStore.filterDictName("eamEquQuantity", scope.row.quantityUnit),
  },
  {
    prop: "assetQuantity",
    label: "数量",
    minWidth: 80,
    isShow: true,
    align: "right",
  },
  {
    prop: "accountDate",
    label: "入账日期",
    minWidth: 100,
    align: "center",
    isShow: true,
    render: (scope: any) =>
      scope.row.accountDate
        ? dayjs(scope.row.accountDate).format("YYYY-MM-DD")
        : "",
  },
  {
    prop: "ratedPower",
    label: "额定功率",
    minWidth: 80,
    isShow: true,
    align: "right",
  },
  {
    prop: "totalPower",
    label: "功率合计",
    minWidth: 80,
    isShow: true,
    align: "right",
  },
  {
    prop: "powerAxis",
    label: "电源所在轴",
    minWidth: 90,
    isShow: true,
    align: "center",
  },
  {
    prop: "manageDepartmentName",
    label: "管理部门",
    minWidth: 100,
    isShow: true,
    align: "center",
  },
  {
    prop: "usingDepartmentName",
    label: "使用部门",
    minWidth: 100,
    isShow: true,
    align: "center",
  },
  {
    prop: "locationName",
    label: "设备位置",
    minWidth: 100,
    isShow: true,
    align: "center",
  },
  {
    prop: "assetImportance",
    label: "设备重要性",
    minWidth: 100,
    align: "center",
    isShow: true,
    render: (scope: any) =>
      dictionaryStore.filterDictName(
        "EquImportance",
        scope.row.assetImportance
      ),
  },

  {
    prop: "measuringType",
    label: "设备类别",
    minWidth: 100,
    align: "center",
    isShow: true,
    render: (scope: any) =>
      dictionaryStore.filterDictName(
        "EquipmentCategory",
        scope.row.measuringType
      ),
  },

  {
    prop: "assetStatus",
    label: "设备状态",
    minWidth: 100,
    isShow: true,
    align: "center",
    render: (scope: any) =>
      useDictionary("EquipStatus", scope.row.assetStatus ?? ""),
  },

  {
    prop: "makerName",
    label: "制造工厂",
    minWidth: 190,
    isShow: true,
    align: "left",
  },
  {
    prop: "makerContactName",
    label: "联系人",
    minWidth: 100,
    isShow: true,
    align: "center",
  },
  {
    prop: "makerContactPhone",
    label: "联系电话",
    minWidth: 120,
    isShow: true,
    align: "center",
  },

  // {
  //   prop: "repairDepartmentName",
  //   label: "维修部门",
  //   minWidth: 110,
  //   isShow: true,
  //   align: "left",
  // },
]);

const searchColumns = ref([]);

// 是否显示搜索框
const showSearch = ref(false);
</script>

<style lang="scss" scoped>
// :deep(.el-form-item--default .el-form-item__label) {
//   // width: 90px !important;
//   justify-content: end !important;
//   padding: 0 7px 0 0;
// }
.zhedie {
  width: 30px;
  height: 28px;
  .el-icon {
    font-size: 16px;
    margin-left: 0px !important;
  }
  svg {
    font-size: 16px !important;
    margin-right: 0px;
  }
}
</style>
